import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, List, message } from 'antd';
import ModalAsync from '@/components/ModalAsync';
import { updatePassword, checkEmailIsCurrent, getCode } from '@/services/user/yonghujiekou';
import { set } from 'lodash';
import { history } from '@umijs/max';

type Unpacked<T> = T extends (infer U)[] ? U : T;

const passwordStrength = {
  strong: <span className="strong">强</span>,
  medium: <span className="medium">中</span>,
  weak: <span className="weak">弱 Weak</span>,
};

const SecurityView: React.FC = () => {
  const [openModal, setOpenModal] = useState<any>(false)
  const [form] = Form.useForm();
  const formRef = useRef<any>();
  const [loadings, setLoadings] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [count, setCount] = useState<number>(60);

  const getData = () => [
    {
      title: '账户密码',
      description: (
        <>
          当前密码强度：
          {passwordStrength.strong}
        </>
      ),
      actions: [<a key="Modify" onClick={() => { setOpenModal(true) }}>修改</a>],
    },
    // {
    //   title: '密保手机',
    //   description: `已绑定手机：138****8293`,
    //   actions: [<a key="Modify">修改</a>],
    // },
    // {
    //   title: '密保问题',
    //   description: '未设置密保问题，密保问题可有效保护账户安全',
    //   actions: [<a key="Set">设置</a>],
    // },
    {
      title: '备用邮箱',
      description: `已绑定邮箱：ant***sign.com`,
      actions: [<a key="Modify">修改</a>],
    },
    // {
    //   title: 'MFA 设备',
    //   description: '未绑定 MFA 设备，绑定后，可以进行二次确认',
    //   actions: [<a key="bind">绑定</a>],
    // },
  ];

  const validateEmailForUser = async () => {
    const email = form.getFieldValue("email")
    if (!email) {
      return Promise.resolve(); // 如果邮箱为空，则不执行验证  
    }
    // 发送请求到后端验证邮箱  
    try {
      const res = await checkEmailIsCurrent({ email: email });
      if (res.code != 0) {
        form.setFields([{ name: 'email', errors: [ res.message??''] }]);
      }
      return true;
    } catch (error) {
      return false;
    }
  }

  const ok = async () => {
    return formRef.current?.submit();
  };

  const handleBlur = async () => {
    try {
      await form.validateFields(['email']);
    } catch (error) {
      console.error('Validation Failed:', error);
    }
  };

  const startCountdown = () => {
    const timer = setInterval(() => {
      setCount((prevCount) => {
        if (prevCount === 1) {
          clearInterval(timer);
          setLoading(false); // 倒计时结束后重置加载状态
        }
        return prevCount - 1;
      });
    }, 1000);
  };

  const handleGetCaptcha = async () => {

  };


  const generateContent = (setLoadings: any) => {
    return (
      <>
        <Form
          ref={formRef}
          form={form}
          layout="vertical"
          onFinish={async (values: any) => {
            const res = await updatePassword(values)
            if (res.code === 0) {
              setOpenModal(false)
              form.resetFields()
              message.success('更新密码成功')
              history.push('/user/login')
            } else {
              message.error(res.message)
              setOpenModal(false)
              form.resetFields()
            }
            setLoadings(false)
          }}
          onFinishFailed={() => setLoadings(false)}
        >
          <Form.Item
            name="oldPassword"
            label="原密码"
            rules={[
              {
                required: true,
                message: '密码不能为空',
              },
              {
                min: 6,
                max: 18,
                message: '密码长度应在6到18个字符之间',
              },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,18}$/,
                message: '密码必须包含字母、数字和特殊字符',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="password"
            label="新密码"
            rules={[
              {
                required: true,
                message: '密码不能为空',
              },
              {
                min: 6,
                max: 18,
                message: '密码长度应在6到18个字符之间',
              },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,18}$/,
                message: '密码必须包含字母、数字和特殊字符',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="checkPassword"
            label="确认密码"
            dependencies={['password']} // 添加依赖项，使得当password变化时，checkPassword的校验也会触发  
            rules={[
              {
                required: true,
                message: '确认密码不能为空',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          
        </Form>
      </>
    )
  }

  const data = getData();
  return (
    <>
      <List<Unpacked<typeof data>>
        itemLayout="horizontal"
        dataSource={data}
        renderItem={(item) => (
          <List.Item actions={item.actions}>
            <List.Item.Meta title={item.title} description={item.description} />
          </List.Item>
        )}
      />

      <ModalAsync
        key={1}
        open={openModal}
        setVisible={setOpenModal}
        title={'修改密码'}
        ok={ok}
        generateContent={generateContent}
      />
    </>
  );
};

export default SecurityView;
